package com.meizu.dao;

import com.meizu.entity.Photo;
import com.meizu.utils.RowMapper;
import com.meizu.utils.SQLHelper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 图片的CRUD的DAO类
 * @author hxf
 * @date 2023/3/23
 **/
public class PhotoDao {
    SQLHelper helper=new SQLHelper();

    /**
     * 根据颜色，版本，商品类别，查图片（局部刷新）
     * @param gid
     * @param dcolor
     * @param dversion
     * @return
     */
    public List<Photo> selectPhotoByCondition(Integer gid,String dcolor,String dversion){
        String sql = "select photo from tb_photo where did=(\n" +
                "select did from tb_detail where gid=? and dcolor=? and dversion=?)";
        return helper.query(sql,new PhotoRowMapper(),gid,dcolor,dversion);
    }
    /**
     * 根据颜色，商品类别，查图片（局部刷新）
     * @param gid
     * @param dcolor
     * @return
     */
    public List<Photo> selectPhotoByConditionTow(Integer gid,String dcolor){
        String sql = "select photo from tb_photo where did=(\n" +
                "select did from tb_detail where gid=? and dcolor=?)";
        return helper.query(sql,new PhotoRowMapper(),gid,dcolor);
    }

    /**
     * 根据商品详情查询对应详情图片
     * @param did 商品详情ID
     * @return 查询结果
     */
    public List<Photo> selectPhoto(Integer did){
        String sql="select photo from tb_photo where did=?";
        return helper.query(sql,new PhotoRowMapper(),did);
    }

    /**
     * 插入商品详情图片
     * @param photo 图片对象
     * @return 插入结果
     */
    public Integer insertPhoto(Photo photo){
        String sql="insert into tb_photo values(null,?,?)";
        return helper.insert(sql,photo.getDid(),
                photo.getPhoto());
    }

    /**
     * 删除商品详情图片
     * @param ids 商品详情ID（多个）
     * @return 返回操作结果
     */
    public Integer deletePhoto(String...ids){
        StringBuilder sb=new StringBuilder("delete from tb_photo where did in ( ");
        for (String id:ids){
            sb.append("?,");
        }
        sb.deleteCharAt(sb.length()-1);
        sb.append(")");
        return helper.update(sb.toString(),ids);
    }
    //查询图片id（后台用）
    public List<Photo> selectPhotoId(Integer did){
        String sql="select pid from tb_photo where did=?";
        return helper.query (sql, new RowMapper<Photo> ( ) {
            @Override
            public Photo map(ResultSet rs) throws SQLException {
                Photo photo=new Photo ();
                photo.setPid (rs.getInt ("pid"));
                return photo;
            }
        },did);
    }
    class PhotoRowMapper implements RowMapper<Photo>{
        @Override
        public Photo map(ResultSet rs) throws SQLException {
            return new Photo(rs.getString("photo"));
        }
    }
}
